package com.lagou.edu.controller;

import com.lagou.edu.pojo.ApiResponse;
import com.lagou.edu.pojo.LoginParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import static com.lagou.edu.interceptor.LoginConstants.USER_KEY;

/**
 * @author leonzhangxf
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    private static final String USERNAME = "admin";
    private static final String PASSWORD = "admin";

    @RequestMapping("/login-page")
    public String loginPage() {
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.setAttribute(USER_KEY, null);
        return "login";
    }

    @PostMapping("/login-submit")
    @ResponseBody
    public ApiResponse<Void> loginSubmit(@RequestBody LoginParams params, HttpSession session) {
        if (!USERNAME.equals(params.getUsername()) || !PASSWORD.equals(params.getPassword())) {
            // login failed
            return ApiResponse.newErr(0, "username or password incorrect");
        }
        // keep session.
        session.setAttribute(USER_KEY, params);
        return ApiResponse.newSuccess(null);
    }
}
